package JHfstools;

import JHfstools.hftedit;
import JHfstools.hftrendlg;

import java.awt.Component;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;

import java.awt.Color;

import javax.swing.JFileChooser;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.JTree;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.UnknownHostException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Calendar;

import javax.swing.JScrollPane;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;

import javax.swing.JCheckBox;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.JProgressBar;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPListParseEngine;
import org.apache.commons.net.io.CopyStreamAdapter;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;

import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.print.PrinterException;

import javax.swing.JSeparator;

import java.awt.Dimension;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

public class hftmain extends JFrame implements Serializable{

	/**
	 * HFS Tools Copyright 2009-2012 David A Thomas  all rights reserved.  May not be used, modified, or copied without permission.
	 * Last version to have rwalker methods.
	 * Changed to use FTPUTIL downloadDirectory and DownloadSingleFile methods.
	 * 05/07 Fixed bug where system name appeared multiple times in drop down.
	 * 05/07 Fixed bug if users cancel out of new directory file chooser dialog.
	 * 05/14 Fixed bug showing FTP error messages uploading file.
	 * 05/14 Fixed bug showing error messages when changing directory on target systems.
	 * 05/14 Fixed bug showing target out of space error messages.
	 * 05/14 Fixed bug when doing file info on remote directory.
	 * 05/18 Fixed directory list bug when switching systems.
	 * 05/28 Moved FTP specific methods to new class hftftp.  
	 **/
	private static final long serialVersionUID = 1L;
	/**
	 * 
	 */
	static JPanel contentPane;
	private DefaultMutableTreeNode root = null;
	static DefaultMutableTreeNode oldtnode = null;
	private static String osname = null;
	private JFileChooser fc = null;
	private JButton hftexitbtn;
	private JButton hfthelpbtn;
	private JButton hftvlogbtn;
	private JButton hftsecbtn;
	private JButton hftconnbtn;
	private JButton hftprtbtn;
	private JButton hftdelbtn;
	private JButton hftrenbtn;
	static JRadioButton hftascbtn;
	static JRadioButton hftbinbtn;
	static JRadioButton hftebcbtn;
	private JCheckBox hftrepbtn;
	private JRadioButton hftrecbtn;
	private JRadioButton hftstrmbtn;
	private JRadioButton hftfilebtn;
	private JRadioButton hftdirbtn;
	private JCheckBox hftpsvbtn;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private final ButtonGroup buttonGroup_1 = new ButtonGroup();
	private final ButtonGroup buttonGroup_2 = new ButtonGroup();
	static JTextField hftstatus;
	static JTree hfttargtree = null;
	private static JButton hftsrc2targ;
	private static JButton hfttarg2src;
	private static JButton hftcopyren;
	private static JButton hftcopycan;
	static boolean gotd = false;
	static dlgdata d = null;
	static JTree hftsrctree;
	static boolean ftpconn = false;
	static DefaultMutableTreeNode rroot = null;
	static DefaultMutableTreeNode originalnode = null;
	static DefaultMutableTreeNode tnode = null;
	private static JToolBar toolBar;
	private static JLabel hftcopyrite;
	static boolean onetree = true;
	private static JScrollPane srctreepane;
	static JProgressBar hftcurrfileprog;
	private static JScrollPane targtreepane;
	private static JPanel panel;
	String odir = null;
	static String idir = null;
	String rfs = null;
	static int pi = 0;
	static long totlength = 0;
	static long totleft = 0;
	static long bytest = 0;
	static long totfiles = 0;
	static long totcopied = 0;
	static JProgressBar hftallfileprog;
	private static JLabel hftstalbl;
	private static JLabel hftcurrftllbl;
	private static JLabel hftallfileslbl;
	static JLayeredPane layeredPane = null;
	String ofn = null;
	static FTPFile newr = null;
	String tpath = null;
	static boolean twindows = false;
	static boolean swindows = false;
	transient OutputStream os = null;
	static boolean reversecopy = false;
	static boolean logopen = false;
	String lasttreeclicked = null;
	static String nfn = null;
	static String singlefilename = null;
	private JSeparator separator;
	private JSeparator separator_1;
	private JSeparator separator_2;
	private JSeparator separator_3;
	//static String remoteDirPath = null;
	static String localDirPath = null;
	static String skippath = null;
	//static int beginnewpath = 0;
	static int dirnewpath = 0;
	static boolean copyerror = false;
	private JButton hftnewfbtn;
	static String rdir= null;
	boolean dontcopy = false;
	static DefaultTreeModel dtm;
	DefaultMutableTreeNode node;
	static String tslash = null;
	static String sslash = null;
	static boolean singlefile = false;
	static boolean Dlgdatachanged = false;
	static boolean ftperror = false;
	static boolean hasconnected = false;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					hftmain frame = new hftmain();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */

	public hftmain() {
		addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent arg0) {
				hftresizestuff();
			}
		});
		setTitle("HFS Tools - The graphical tool for manipulating HFS and ZFS files.");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 1024, 860);
		contentPane = new JPanel();
		contentPane.setBackground(new Color(245, 255, 250));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		d = new dlgdata();
		osname = System.getProperty("os.name");
		if (osname.indexOf("Windows") != -1){swindows = true; sslash="\\";}
		else{sslash="/";}
	      try
	      {   	  
	         FileInputStream fileIn =
	                          new FileInputStream("hft.ser");
	         ObjectInputStream in = new ObjectInputStream(fileIn);
	         d = (dlgdata) in.readObject();
	         in.close();
	         fileIn.close();
	         gotd = true;
	      }catch(IOException i)
	      {d = new dlgdata();
	      
	      }catch(ClassNotFoundException c)
	      {
	         System.out.println("hft.ser not found");
	         d = new dlgdata();
	         return;
	      }
		
		layeredPane = new JLayeredPane();
		layeredPane.setPreferredSize(new Dimension(1024, 815));
		layeredPane.setBounds(0, 0, 1024, 815);
		contentPane.add(layeredPane);
		
		toolBar = new JToolBar();
		toolBar.setBounds(7, 6, 990, 59);
		layeredPane.setLayer(toolBar, 1);
		layeredPane.add(toolBar);
		
		JButton hfteditbtn = new JButton("Edit       ");
		hfteditbtn.setToolTipText("Edit selected file");
		hfteditbtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				doedit();
					}
		});
		hfteditbtn.setVerticalTextPosition(SwingConstants.BOTTOM);
		hfteditbtn.setHorizontalTextPosition(SwingConstants.CENTER);
		hfteditbtn.setIcon(new ImageIcon(this.getClass().getResource("images/eicon.png")));
		toolBar.add(hfteditbtn);
		
		hftrenbtn = new JButton("Rename ");
		hftrenbtn.setToolTipText("Rename selected file");
		hftrenbtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			dorename();
			}
			
		});
		hftrenbtn.setVerticalTextPosition(SwingConstants.BOTTOM);
		hftrenbtn.setHorizontalTextPosition(SwingConstants.CENTER);
		hftrenbtn.setIcon(new ImageIcon(hftmain.class.getResource("images/renicon.png")));
		toolBar.add(hftrenbtn);
		
		hftdelbtn = new JButton("Delete    ");
		hftdelbtn.setToolTipText("Delete selected file");
		hftdelbtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dodelete();
			}
			
		});
		hftdelbtn.setVerticalTextPosition(SwingConstants.BOTTOM);
		hftdelbtn.setHorizontalTextPosition(SwingConstants.CENTER);
		hftdelbtn.setIcon(new ImageIcon(hftmain.class.getResource("images/dicon.png")));
		toolBar.add(hftdelbtn);
		
		hftprtbtn = new JButton("Print       ");
		hftprtbtn.setEnabled(false);
		hftprtbtn.setToolTipText("Print selected file");
		hftprtbtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				doprint();
			}
		});
		
		hftnewfbtn = new JButton("Directory ");
		hftnewfbtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				donewdir();
			}
		});
		hftnewfbtn.setToolTipText("Create a new directory in the selected directory.");
		hftnewfbtn.setHorizontalTextPosition(SwingConstants.CENTER);
		hftnewfbtn.setVerticalTextPosition(SwingConstants.BOTTOM);
		hftnewfbtn.setIcon(new ImageIcon(this.getClass().getResource("images/foldernew.png")));
		toolBar.add(hftnewfbtn);
		hftprtbtn.setVerticalTextPosition(SwingConstants.BOTTOM);
		hftprtbtn.setHorizontalTextPosition(SwingConstants.CENTER);
		hftprtbtn.setIcon(new ImageIcon(hftmain.class.getResource("images/picon.png")));
		toolBar.add(hftprtbtn);
		
		hftconnbtn = new JButton("Connect  ");
		hftconnbtn.setToolTipText("Connect to remote system");
		hftconnbtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				doconnect();
			}
		});
		hftconnbtn.setVerticalTextPosition(SwingConstants.BOTTOM);
		hftconnbtn.setHorizontalTextPosition(SwingConstants.CENTER);
		hftconnbtn.setIcon(new ImageIcon(hftmain.class.getResource("images/cnicon.png")));
		toolBar.add(hftconnbtn);
		
		hftsecbtn = new JButton("Security   ");
		hftsecbtn.setToolTipText("Change security settings");
		hftsecbtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				dosecurity();
			}
		});
		hftsecbtn.setVerticalTextPosition(SwingConstants.BOTTOM);
		hftsecbtn.setHorizontalTextPosition(SwingConstants.CENTER);
		hftsecbtn.setIcon(new ImageIcon(hftmain.class.getResource("images/sicon.png")));
		toolBar.add(hftsecbtn);
		
		hftvlogbtn = new JButton("View Log");
		hftvlogbtn.setToolTipText("View the log");
		hftvlogbtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				doviewlog();
			}
		});
		
		JButton btnFileInfo = new JButton("File Info  ");
		btnFileInfo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				doinfo();
			}
		});
		btnFileInfo.setVerticalTextPosition(SwingConstants.BOTTOM);
		btnFileInfo.setHorizontalTextPosition(SwingConstants.CENTER);
		btnFileInfo.setIcon(new ImageIcon(hftmain.class.getResource("images/fileinfo.png")));
		toolBar.add(btnFileInfo);
		hftvlogbtn.setVerticalTextPosition(SwingConstants.BOTTOM);
		hftvlogbtn.setHorizontalTextPosition(SwingConstants.CENTER);
		hftvlogbtn.setIcon(new ImageIcon(hftmain.class.getResource("images/view_log.png")));
		toolBar.add(hftvlogbtn);
		
		hfthelpbtn = new JButton("Help       ");
		hfthelpbtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				dohelp();
			}
		});
		hfthelpbtn.setToolTipText("Get help");
		hfthelpbtn.setVerticalTextPosition(SwingConstants.BOTTOM);
		hfthelpbtn.setHorizontalTextPosition(SwingConstants.CENTER);
		hfthelpbtn.setIcon(new ImageIcon(hftmain.class.getResource("images/hicon.png")));
		toolBar.add(hfthelpbtn);
		
		hftexitbtn = new JButton("Exit       ");
		hftexitbtn.setToolTipText("Exit HFS Tools");
		hftexitbtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				doexit();
			}
		});
		hftexitbtn.setVerticalTextPosition(SwingConstants.BOTTOM);
		hftexitbtn.setHorizontalTextPosition(SwingConstants.CENTER);
		hftexitbtn.setIcon(new ImageIcon(hftmain.class.getResource("images/xicon.png")));
		toolBar.add(hftexitbtn);
		
		panel = new JPanel();
		panel.setBounds(13, 75, 1001, 23);
		layeredPane.setLayer(panel, 1);
		layeredPane.add(panel);
		GridBagLayout gbl_panel = new GridBagLayout();
		gbl_panel.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
		gbl_panel.rowHeights = new int[]{0, 0};
		gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		gbl_panel.rowWeights = new double[]{1.0, Double.MIN_VALUE};
		panel.setLayout(gbl_panel);
		
		hftascbtn = new JRadioButton("ASCII");
		hftascbtn.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if (hftascbtn.isSelected() && ftpconn){
					try {
						hftftp.ftp.setFileType(FTP.ASCII_FILE_TYPE);
						System.out.println(hftftp.ftp.getReplyString());
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
				}
			}
		});
		hftascbtn.setToolTipText("Set ASCII transfer mode");
		buttonGroup.add(hftascbtn);
		GridBagConstraints gbc_hftascbtn = new GridBagConstraints();
		gbc_hftascbtn.insets = new Insets(0, 0, 0, 5);
		gbc_hftascbtn.gridx = 0;
		gbc_hftascbtn.gridy = 0;
		panel.add(hftascbtn, gbc_hftascbtn);
		
		hftbinbtn = new JRadioButton("Binary");
		hftbinbtn.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if (hftbinbtn.isSelected() && ftpconn){
					try {
						hftftp.ftp.setFileType(FTP.BINARY_FILE_TYPE);
						System.out.println(hftftp.ftp.getReplyString());
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		});
		hftbinbtn.setSelected(true);
		hftbinbtn.setToolTipText("Set Binary transfer mode");
		buttonGroup.add(hftbinbtn);
		GridBagConstraints gbc_hftbinbtn = new GridBagConstraints();
		gbc_hftbinbtn.insets = new Insets(0, 0, 0, 5);
		gbc_hftbinbtn.gridx = 1;
		gbc_hftbinbtn.gridy = 0;
		panel.add(hftbinbtn, gbc_hftbinbtn);
		
		hftebcbtn = new JRadioButton("EBCDIC");
		hftebcbtn.setToolTipText("Set EBCDIC transfer mode (mainframe to mainframe transfer only)");
		buttonGroup.add(hftebcbtn);
		GridBagConstraints gbc_hftebcbtn = new GridBagConstraints();
		gbc_hftebcbtn.insets = new Insets(0, 0, 0, 5);
		gbc_hftebcbtn.gridx = 2;
		gbc_hftebcbtn.gridy = 0;
		panel.add(hftebcbtn, gbc_hftebcbtn);
		
		separator = new JSeparator();
		separator.setMinimumSize(new Dimension(2, 20));
		separator.setSize(new Dimension(4, 20));
		separator.setOrientation(SwingConstants.VERTICAL);
		separator.setForeground(Color.BLACK);
		separator.setPreferredSize(new Dimension(8, 20));
		GridBagConstraints gbc_separator = new GridBagConstraints();
		gbc_separator.insets = new Insets(0, 0, 0, 5);
		gbc_separator.gridx = 3;
		gbc_separator.gridy = 0;
		panel.add(separator, gbc_separator);
		
		hftpsvbtn = new JCheckBox("Passive");
		hftpsvbtn.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				boolean is = hftpsvbtn.isSelected();
				if (hftpsvbtn.isSelected() && ftpconn){
					hftftp.ftp.enterLocalPassiveMode();
					System.out.println("Connection is now in passive mode.");
				}
				if (!hftpsvbtn.isSelected() && ftpconn){
					hftftp.ftp.enterLocalActiveMode();
					System.out.println("Connection is now in active mode.");
				}
			}
		});
		hftpsvbtn.setToolTipText("Use FTP Passive mode");
		//hftpsvbtn.setSelected(true);
		GridBagConstraints gbc_hftpsvbtn = new GridBagConstraints();
		gbc_hftpsvbtn.insets = new Insets(0, 0, 0, 5);
		gbc_hftpsvbtn.gridx = 4;
		gbc_hftpsvbtn.gridy = 0;
		panel.add(hftpsvbtn, gbc_hftpsvbtn);
		
		hftrepbtn = new JCheckBox("Replace");
		hftrepbtn.setToolTipText("Replace duplicate files");
		GridBagConstraints gbc_hftrepbtn = new GridBagConstraints();
		gbc_hftrepbtn.insets = new Insets(0, 0, 0, 5);
		gbc_hftrepbtn.gridx = 5;
		gbc_hftrepbtn.gridy = 0;
		panel.add(hftrepbtn, gbc_hftrepbtn);
		
		separator_1 = new JSeparator();
		separator_1.setMinimumSize(new Dimension(2, 20));
		separator_1.setForeground(Color.BLACK);
		separator_1.setPreferredSize(new Dimension(4, 20));
		separator_1.setOrientation(SwingConstants.VERTICAL);
		GridBagConstraints gbc_separator_1 = new GridBagConstraints();
		gbc_separator_1.insets = new Insets(0, 0, 0, 5);
		gbc_separator_1.gridx = 6;
		gbc_separator_1.gridy = 0;
		panel.add(separator_1, gbc_separator_1);
		
		hftrecbtn = new JRadioButton("Record");
		hftrecbtn.setToolTipText("Transfer files in record mode");
		buttonGroup_1.add(hftrecbtn);
		GridBagConstraints gbc_hftrecbtn = new GridBagConstraints();
		gbc_hftrecbtn.insets = new Insets(0, 0, 0, 5);
		gbc_hftrecbtn.gridx = 7;
		gbc_hftrecbtn.gridy = 0;
		panel.add(hftrecbtn, gbc_hftrecbtn);
		
		hftstrmbtn = new JRadioButton("Stream");
		hftstrmbtn.setToolTipText("Transfer files in stream mode");
		hftstrmbtn.setSelected(true);
		buttonGroup_1.add(hftstrmbtn);
		GridBagConstraints gbc_hftstrmbtn = new GridBagConstraints();
		gbc_hftstrmbtn.insets = new Insets(0, 0, 0, 5);
		gbc_hftstrmbtn.gridx = 8;
		gbc_hftstrmbtn.gridy = 0;
		panel.add(hftstrmbtn, gbc_hftstrmbtn);
		
		separator_2 = new JSeparator();
		separator_2.setMinimumSize(new Dimension(2, 20));
		separator_2.setForeground(Color.BLACK);
		separator_2.setPreferredSize(new Dimension(4, 20));
		separator_2.setOrientation(SwingConstants.VERTICAL);
		GridBagConstraints gbc_separator_2 = new GridBagConstraints();
		gbc_separator_2.insets = new Insets(0, 0, 0, 5);
		gbc_separator_2.gridx = 9;
		gbc_separator_2.gridy = 0;
		panel.add(separator_2, gbc_separator_2);
		
		hftfilebtn = new JRadioButton("File");
		hftfilebtn.setToolTipText("List files and directories");
		hftfilebtn.setSelected(true);
		buttonGroup_2.add(hftfilebtn);
		GridBagConstraints gbc_hftfilebtn = new GridBagConstraints();
		gbc_hftfilebtn.insets = new Insets(0, 0, 0, 5);
		gbc_hftfilebtn.gridx = 10;
		gbc_hftfilebtn.gridy = 0;
		panel.add(hftfilebtn, gbc_hftfilebtn);
		
		hftdirbtn = new JRadioButton("Directory");
		hftdirbtn.setToolTipText("List directories only");
		buttonGroup_2.add(hftdirbtn);
		GridBagConstraints gbc_hftdirbtn = new GridBagConstraints();
		gbc_hftdirbtn.insets = new Insets(0, 0, 0, 5);
		gbc_hftdirbtn.gridx = 11;
		gbc_hftdirbtn.gridy = 0;
		panel.add(hftdirbtn, gbc_hftdirbtn);
		
		separator_3 = new JSeparator();
		separator_3.setMinimumSize(new Dimension(2, 20));
		separator_3.setForeground(Color.BLACK);
		separator_3.setPreferredSize(new Dimension(4, 20));
		separator_3.setOrientation(SwingConstants.VERTICAL);
		GridBagConstraints gbc_separator_3 = new GridBagConstraints();
		gbc_separator_3.insets = new Insets(0, 0, 0, 5);
		gbc_separator_3.gridx = 12;
		gbc_separator_3.gridy = 0;
		panel.add(separator_3, gbc_separator_3);
		
		srctreepane = new JScrollPane();
		srctreepane.setBounds(13, 109, 443, 390);
		layeredPane.setLayer(srctreepane, 2);
		layeredPane.add(srctreepane);
		if (osname.equals("z/OS")){
			rfs = "/etc/";
		}else{
		rfs = "C:/";
		}
		root = new DefaultMutableTreeNode("..",true);
		getList(root, new File(rfs));
		String shn = null;
		try{
			shn = java.net.InetAddress.getLocalHost().getHostName();
			d.sethn(shn);

					}
		catch (UnknownHostException e){ 
			shn = null;
		}
		
		
		hftsrctree = new JTree(root);
		hftsrctree.setToolTipText("Source to copy files from");
		hftsrctree.setBorder(new TitledBorder(null, shn, TitledBorder.LEADING, TitledBorder.TOP, null, null));
		hftsrctree.setCellRenderer(new MyTreeCellRenderer());
		
		hftsrctree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent arg0) {
				DefaultMutableTreeNode node = (DefaultMutableTreeNode)
	                	hftsrctree.getLastSelectedPathComponent();
				if (node == null){
					return; // nothing was selected
				}
				d.setltc("source");
				DefaultMutableTreeNode sp = new DefaultMutableTreeNode(node.getParent());
				String sel = (String) node.toString();
				d.setsel(sel);
				d.setparent(sp);
				d.setfl("local");
				File nrf = null;
				if (sel.equals("..")){
					fc = new JFileChooser();
					fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					int returnVal = fc.showOpenDialog(layeredPane);
					if (returnVal == JFileChooser.APPROVE_OPTION) {
						nrf = fc.getSelectedFile();
					}
					if (nrf != null){
					nfn = nrf.toString();
					nfn.replaceAll("//", "/");
					System.out.println("nfn is "+nfn);
					}
					if (nrf == null) {
						//nrf = new File(node.toString());
						nrf = new File(rfs);
						if (nrf.isDirectory()){
						getList(node, nrf);}
					}
					DefaultMutableTreeNode dtn = new DefaultMutableTreeNode("..");
					DefaultTreeModel dtm = new DefaultTreeModel(dtn);
					hftsrctree.setModel(dtm);
					getList(dtn, nrf);
					dtm.reload();
					invalidate();
				}
				else{
					nrf = new File(node.toString());
					if (nrf.isDirectory()){
					getList(node, nrf);
					}else {return;}
				}
				d.setsel(sel);
				d.setparent(sp);
				d.setfl("local");
			}
		});
			
		srctreepane.setViewportView(hftsrctree);

		hftcopyrite = new JLabel("Copyright \u00a9 2009-2012 David A Thomas");
		hftcopyrite.setBounds(396, 790, 264, 14);
		layeredPane.setLayer(hftcopyrite, 1);
		layeredPane.add(hftcopyrite);
		
		hftstatus = new JTextField();
		hftstatus.setToolTipText("HFS Tools current status");
		hftstatus.setBounds(124, 759, 873, 20);
		layeredPane.setLayer(hftstatus, 1);
		layeredPane.add(hftstatus);
		hftstatus.setColumns(10);
		hftstatus.setText("Waiting for user...");
		if (osname.equals("z/OS")){
			hftstatus.setBounds(124, 785, 873, 20);
			}

		
		hftcurrfileprog = new JProgressBar();
		hftcurrfileprog.setForeground(Color.BLUE);
		hftcurrfileprog.setToolTipText("Progress transferring the current file");
		hftcurrfileprog.setBounds(124, 597, 873, 19);
		hftcurrfileprog.setStringPainted(true);
		layeredPane.setLayer(hftcurrfileprog, 1);
		layeredPane.add(hftcurrfileprog);
		
		hftallfileprog = new JProgressBar();
		hftallfileprog.setForeground(Color.BLUE);
		hftallfileprog.setToolTipText("Progress of all file transfers");
		hftallfileprog.setBounds(124, 641, 873, 19);
		hftallfileprog.setStringPainted(true);
		layeredPane.setLayer(hftallfileprog, 1);
		layeredPane.add(hftallfileprog);
		
		hftstalbl = new JLabel("Status:");
		hftstalbl.setBounds(45, 762, 61, 14);
		if (osname.equals("z/OS")){
			hftstalbl.setBounds(45, 785, 61, 14);
			}
		layeredPane.setLayer(hftstalbl, 1);
		layeredPane.add(hftstalbl);
		
		hftcurrftllbl = new JLabel("Current File:");
		hftcurrftllbl.setBounds(31, 597, 94, 14);
		layeredPane.setLayer(hftcurrftllbl, 1);
		layeredPane.add(hftcurrftllbl);
		
		hftallfileslbl = new JLabel("All Files:");
		hftallfileslbl.setBounds(31, 641, 65, 14);
		layeredPane.setLayer(hftallfileslbl, 1);
		layeredPane.add(hftallfileslbl);
		
		hftsrc2targ = new JButton("");
		hftsrc2targ.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				hftftp.dobg();
			}
		});
		hftsrc2targ.setToolTipText("Copy source system files to target system");
		layeredPane.setLayer(hftsrc2targ, 1);
		hftsrc2targ.setIcon(new ImageIcon(hftmain.class.getResource("images/copysrc.png")));
		hftsrc2targ.setBounds(466, 158, 40, 41);
		
		layeredPane.add(hftsrc2targ);
		
		hfttarg2src = new JButton("");
		hfttarg2src.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				reversecopy=true;
				hftftp.dobg();
			}
		});
		hfttarg2src.setToolTipText("Copy target system files to source system");
		hfttarg2src.setIcon(new ImageIcon(hftmain.class.getResource("images/copytarg.png")));
		hfttarg2src.setBounds(466, 256, 40, 41);
		layeredPane.setLayer(hfttarg2src, 1);
		layeredPane.add(hfttarg2src);
		
		hftcopyren = new JButton("");
		hftcopyren.setToolTipText("Copy source system file to target system and rename it");
		hftcopyren.setIcon(new ImageIcon(hftmain.class.getResource("images/copy_ren.png")));
		hftcopyren.setBounds(466, 368, 40, 41);
		layeredPane.setLayer(hftcopyren, 1);
		layeredPane.add(hftcopyren);
		
		hftcopycan = new JButton("");
		hftcopycan.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				docopycan();
			}
		});
		hftcopycan.setToolTipText("Disconnect from remote system and return to main screen");
		hftcopycan.setIcon(new ImageIcon(hftmain.class.getResource("/JHfstools/images/dcicon.png")));
		hftcopycan.setBounds(466, 480, 40, 41);
		layeredPane.setLayer(hftcopycan, 1);
		layeredPane.add(hftcopycan);
		
		targtreepane = new JScrollPane();
		layeredPane.add(targtreepane);
		hfttargtree = new JTree(rroot);
		hfttargtree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {
				tnode = (DefaultMutableTreeNode)
	                	hfttargtree.getLastSelectedPathComponent();
				if (tnode == null){
					return; // nothing was selected
				}
				hftstatus.setText("TreeSelectionListener invoked");
				if (tnode != null && ftpconn == true){
					hftftp.doFTPTargtreeclicked(tnode);
				}
			}
		});
		}
	
	
	public void setdlgdatachanged(boolean value){
		Dlgdatachanged = value;
	}
	
	public void doviewlog(){
		d.setsel("ftplog.txt"); //set name for edit dialog
		d.setfl("local"); // it is a local file
		d.setlogfl(true); // set it as a log file
		hftedit edit = new hftedit(d, hftftp.ftp); // invoke edit dialog
		edit.pack(); // pack it and display it.
		edit.setLocationRelativeTo(null);
		edit.setVisible(true);
	}// end function
	
	public void doprint(){
		if (hftsrctree.getLastSelectedPathComponent() == null && hfttargtree.getLastSelectedPathComponent() == null){
		JOptionPane.showMessageDialog(contentPane,"Please select a file to print.","Print error",JOptionPane.ERROR_MESSAGE);
		return;
		}
		JEditorPane printpane = new JEditorPane();
		printpane.setVisible(false);
		FileInputStream fis = null;
		if(d.getfl() == "local"){ // it's a local file
		try {
			fis = new FileInputStream(d.getsel());
			printpane.read(fis, null);
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}else{// it's a remote file
	try{
		InputStream is = hftftp.ftp.retrieveFileStream(d.getsel());
		printpane.read(is, null);
		is.close();
	}catch(IOException e){
		e.printStackTrace();
	}
	}
	try{
		printpane.print();
	}catch (PrinterException pe){
		pe.printStackTrace();
	}
	}
	
	public void dorename(){ // check to see if a tree node was selected
		String nfn = null;
		if (ftpconn){
		if (hftsrctree.getLastSelectedPathComponent() == null && hfttargtree.getLastSelectedPathComponent() == null){
		JOptionPane.showMessageDialog(contentPane,"Please select a file to rename.","Rename error",JOptionPane.ERROR_MESSAGE);
		return;
		}
		}else{
			if (hftsrctree.getLastSelectedPathComponent() == null){
				JOptionPane.showMessageDialog(contentPane,"Please select a file to rename.","Rename error",JOptionPane.ERROR_MESSAGE);
				return;	
			}
		}
		if (d.getltc()=="source"){// its a local file
		File tf = new File(d.getsel()); // create a file object to manipulate
		String tp = tf.getParent(); // get the file parent directory
		hftrendlg ren = new hftrendlg(); // pop up a dialog to get the newname
		ren.setLocationRelativeTo(null);
		ren.pack();
		ren.setVisible(true);
		String newn = null;
		if (ren.gethftnewnamebox().getText() != null){
		if (swindows){
		newn = tp+"\\"+ren.gethftnewnamebox().getText(); // retrieve the new name from the dialog object
		}else{
			newn = tp+"/"+ren.gethftnewnamebox().getText(); // retrieve the new name from the dialog object	
		}
		// create a tree node with the new name
		DefaultMutableTreeNode nn = new DefaultMutableTreeNode(newn);
		ren.dispose(); // get rid of the dialog
		boolean rename = tf.renameTo(new File(newn)); // rename the file
		// create a tree model we can manipulate
		DefaultTreeModel model = (DefaultTreeModel) hftsrctree.getModel();
		// get the node with the old name
		DefaultMutableTreeNode node = (DefaultMutableTreeNode)
            	hftsrctree.getLastSelectedPathComponent();
		if (hftsrctree.isSelectionEmpty() && hfttargtree.isSelectionEmpty()){
			JOptionPane.showMessageDialog(contentPane,"Please select a file to rename.","Rename error",JOptionPane.ERROR_MESSAGE);	
		}
		else{	
		node.setUserObject(nn); // add the new node
		model.nodeChanged(node); // and update the tree
		}
		}else
			ren.dispose(); // user cancelled the name change on the dialog so just get rid of the dialog
		hftstatus.setText(tf.getName()+" was renamed to "+newn);
		return;
		}
		if (d.getltc()=="target"){// it is a remote file
			DefaultMutableTreeNode node = (DefaultMutableTreeNode)
	            	hfttargtree.getLastSelectedPathComponent();
			FTPFile tf = new FTPFile(); // create new empty file on the remote system 
			if (node.isLeaf()){
			try {
				String fn = hftftp.ftp.printWorkingDirectory()+"/"+node.toString();
				FTPFile[] tfa = hftftp.ftp.listFiles(fn); //try to list the file; this returns a file array
				tf = tfa[0]; // if our file exists, it is the first one in the array
			} catch (IOException e) {
				System.out.println("Remote file not found.");
				hftstatus.setText("Rename error occured, check log.");
			}
			nfn = tf.getName(); // get file name
			//nfn = node.toString();
			}else
				nfn = node.toString();
			hftrendlg ren = new hftrendlg(); // pop up a dialog to get the new name.
			ren.setLocationRelativeTo(null);
			ren.pack();
			ren.setVisible(true);
			String newn = " ";
			if (ren.gethftnewnamebox().getText() != null){
				try { // retrieve new name from dialog object
					if (!node.isLeaf()){hftftp.ftp.cdup();}
					newn = hftftp.ftp.printWorkingDirectory()+"/"+ren.gethftnewnamebox().getText();
					boolean rc = hftftp.ftp.rename(nfn, newn); // rename the file on the remote system
				} catch (IOException e) {
					e.printStackTrace();
				}
				// create a new tree node for our renamed file.
				DefaultMutableTreeNode nn = new DefaultMutableTreeNode(ren.gethftnewnamebox().getText());
				ren.dispose(); // get rid of dialog box
				DefaultTreeModel model = (DefaultTreeModel) hfttargtree.getModel(); // create a model object for our tree
				// get the old treee node 
				node.setUserObject(nn); // insert the new node
				model.nodeChanged(node); // update the model to show the changes
				hftstatus.setText(nfn+" has been renamed to "+newn);
			}else {
				ren.dispose(); // user cancelled rename, just get rid of the dialog
			}
		}
		return;
	}
	
	void dodelete(){
		DefaultTreeModel model= null;
		DefaultMutableTreeNode node = null;
		DefaultMutableTreeNode pnode = null;
		String dn = null;
		boolean isdir = false;

		Object[] options = { "OK", "CANCEL" };
		if (d.getfl() == "local"){// its a local file
		model = (DefaultTreeModel) hftsrctree.getModel();  // get a tree model to update
		node = (DefaultMutableTreeNode) // get the node that had the file in it
	           	hftsrctree.getLastSelectedPathComponent();
		if (!node.isRoot()){
		pnode = (DefaultMutableTreeNode) node.getParent();
		if (pnode.toString()!="." && pnode.toString()!= ".."){
		if (twindows){
		dn = pnode.toString()+"\\"+node.toString();
		}else{
		dn = pnode.toString()+"/"+node.toString();
		}
		}
		else {dn = node.toString();}
		}
		File df = new File(dn); // create a new file object to manipulate
		boolean ft = df.isFile();
		ft = df.isDirectory();
			if (df.isFile()){
				// put up the confirmation dialog
				int n = JOptionPane.showOptionDialog(null, "Really delete file "+d.getsel(), "Warning",
				        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
				        null, options, options[0]);
				if (n == 0){df.delete();}
				}
			if (df.isDirectory()){
				// put up the confirmation dialog
				int n = JOptionPane.showOptionDialog(null, d.getsel()+" is a directory.  Really delete it?", "Warning",
				        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
				        null, options, options[0]);
				dirdelete(df);
				hftstatus.setText("Directory "+dn+" was deleted.");
				}
		}else {// its a remote file
			node = (DefaultMutableTreeNode) // get the node that had the file in it
		           	hfttargtree.getLastSelectedPathComponent();
				if (!node.isLeaf()){isdir = true;}
				FTPFile file = new FTPFile();
				try {
					System.out.println("Currdir is "+hftftp.ftp.pwd());
					if(isdir){hftftp.ftp.cdup();}
					System.out.println("Currdir is "+hftftp.ftp.pwd());
			    	FTPListParseEngine engine = hftftp.ftp.initiateListParsing("UnixFTPEntryParser", "-al");
					FTPFile[] tfa = engine.getFiles(); //try to list the file; this returns a file array
					System.out.println("Currdir is "+hftftp.ftp.pwd());
					for (FTPFile temp : tfa){
						System.out.println("temp = "+temp);
						if (temp.getName().equals(d.getsel())){file = temp;}
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					System.out.println("Remote file not found.");
					hftstatus.setText("Delete error occured, check log.");
				}

				System.out.println("File name is: "+file.getName());
				if (file.isDirectory()){
					int rc = 0;
					int n = JOptionPane.showOptionDialog(null, d.getsel()+" is a directory.  Really delete it?", "Warning",
					        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
					        null, options, options[0]);
					try {
						String filepath = file.getName();
						System.out.println("File path is: "+filepath);
						FTPFile[] fa = hftftp.ftp.listFiles(filepath);
						if (fa.length == 0){
							if (n !=0) {return;}
							if (n == 0) {hftftp.ftp.removeDirectory(filepath);}
						}else{
						if (n!=0){return;}	
						if (n==0){hftftp.FTPUtil.removeDirectory(hftftp.ftp, filepath, "");}
						rc = hftftp.ftp.getReplyCode();
						if (rc == 250){hftstatus.setText("Directory "+filepath+" deleted.");}
						if (rc != 250){hftstatus.setText("Directory "+filepath+" not deleted, check Log.");}
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					}
				else{// its a file so just delete it.
					int n = JOptionPane.showOptionDialog(null, "Really delete file "+d.getsel(), "Warning",
					        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
					        null, options, options[0]);
					System.out.println("File name is: "+file.getName());
					boolean rc = false;
					try {
						 if (n !=0){return;}
						 if (n==0){rc=hftftp.ftp.deleteFile(file.getName());}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("RC was: "+rc);
				}
				model = (DefaultTreeModel) hfttargtree.getModel();
				node = (DefaultMutableTreeNode)
	                	hfttargtree.getLastSelectedPathComponent();
			
			
		}
		model.removeNodeFromParent(node);
	}
	void dirdelete(File df){
		if (df.isDirectory()){
		if (df.list().length == 0){df.delete();} //if directory is empty, just delete it.
		else{
			String files[] = df.list();
			for (String temp : files){
				File filedelete = new File(df,temp);
				//recursive delete
				dirdelete(filedelete);
			}
			//check length again, if directory is empty, nuke it
			if (df.list().length==0){
					df.delete();
			}
		}
		}// end of isdirectory
		else{// if it is a file just delete it.
			df.delete();
		}
	}

	void donewdir(){
		if (ftpconn){
		if (hftsrctree.getLastSelectedPathComponent() == null && hfttargtree.getLastSelectedPathComponent() == null){
		JOptionPane.showMessageDialog(contentPane,"Please select a directory first.","Create Directory error",JOptionPane.ERROR_MESSAGE);
		return;
		}
		}else{
			if (hftsrctree.getLastSelectedPathComponent() == null){
				JOptionPane.showMessageDialog(contentPane,"Please select a directory first.","Create Directory error",JOptionPane.ERROR_MESSAGE);
				return;	
			}
		}
		hftdirdlg dd = new hftdirdlg();
		dd.pack();
		dd.setLocationRelativeTo(null);
		dd.setVisible(true);
		if (dd.getdirdlgrc()== false){return;}
		String newdirname = dd.getHftdirdlgname().getText();
		String newfilename = null;
		boolean mdrc = false;
		if (d.getltc() == "target"){
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) hfttargtree.getLastSelectedPathComponent();
			DefaultTreeModel model = (DefaultTreeModel) hfttargtree.getModel();
		try {
			mdrc = hftftp.ftp.makeDirectory(newdirname);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		DefaultMutableTreeNode newnode = new DefaultMutableTreeNode(newdirname);
		node.add(newnode);
		model.reload();
		if (mdrc == true){hftstatus.setText("Directory "+newdirname+" was created in "+node.toString());}
		return;
		}else{
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) hftsrctree.getLastSelectedPathComponent();
			DefaultTreeModel model = (DefaultTreeModel) hftsrctree.getModel();
			DefaultMutableTreeNode newnode = new DefaultMutableTreeNode(newdirname);
			if (twindows){
			newfilename = node.toString()+"\\"+newdirname;
			}else{
			newfilename = node.toString()+"/"+newdirname;
			}
			//File nodefile = new File(newfilename);
			mdrc = new File(newfilename).mkdirs();
			node.add(newnode);
			model.reload();
			if (mdrc == true){hftstatus.setText("Directory "+newdirname+" was created in "+node.toString());}
			return;
		}
	}
	
	void doconnect(){
		int z = 0;
		if (d.gettrantype().equals("ftp")){
		hftftp.ftpsetup();
		
		}
		if (d.gettrantype().equals("sftp")){
		hftssh.jschsetup();
		}
		hftstatus.setText("Connected to "+d.Targsys);
		onetree = false;
		if (hasconnected){
			dtm.nodeChanged(rroot);
			dtm.nodeStructureChanged(rroot);
			dtm.setRoot(null);
			dtm.setRoot(rroot);
        	dtm.nodeChanged(rroot);
			dtm.reload();
			dtm.nodeStructureChanged(rroot);
			dtm.nodeChanged(rroot);
			invalidate();
		}
		hfttargtree.setLocation(480, 53);
		targtreepane.setBounds(552, 109, 443, 464);
		targtreepane.setLocation(450, 53);
		if (!hasconnected){
		dtm = (DefaultTreeModel) hfttargtree.getModel();
		dtm.setRoot(rroot);
		dtm.reload();}
		layeredPane.setLayer(targtreepane, 1);
		hfttargtree.setCellRenderer(new MyTreeCellRenderer());
		/*hfttargtree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {
				node = (DefaultMutableTreeNode)
	                	hfttargtree.getLastSelectedPathComponent();
				if (node == null){
					return; // nothing was selected
				}*/
				//hftstatus.setText("TreeSelectionListener invoked");

		int newh = layeredPane.getHeight();
		int neww = layeredPane.getWidth();
		targtreepane.setViewportView(hfttargtree);
		hfttargtree.setBorder(new TitledBorder(null, d.Targsys, TitledBorder.LEADING, TitledBorder.TOP, null, null));
		hfttargtree.setToolTipText("Remote system files");
		layeredPane.setLayer(hfttargtree, 1);
		srctreepane.setLocation(15, 105);
		panel.setSize(960,23);
		srctreepane.setSize(425,580);
		hftsrctree.setSize(425,580);
		hfttargtree.setSize(425,580);
		targtreepane.setSize(425,580);
		targtreepane.setLocation(570, 105);
		hftstalbl.setLocation(15,newh-54);
		hftstatus.setLocation(95,newh-55);
		hftstatus.setSize(neww-130,hftstatus.getHeight());
		hftcurrftllbl.setLocation(15,newh-114);
		hftallfileslbl.setLocation(15, newh-84);
		hftcurrfileprog.setLocation(95,newh-115);
		hftcurrfileprog.setSize(neww-130,hftcurrfileprog.getHeight());
		hftallfileprog.setSize(neww-130,hftallfileprog.getHeight());
		hftallfileprog.setLocation(95,newh-85);		
		hftsrc2targ.setLocation(490, 195);
		hfttarg2src.setLocation(490, 305);
		hftcopyren.setLocation(490,430);
		hftcopycan.setLocation(490,550);
		hasconnected=true;
	}
	
	void doexit(){
		File temp = new File("hft.ser");
		if (temp.exists()){temp.delete();
		}
		File ser = new File("hft.ser");
		try{
			FileOutputStream fileOut = new FileOutputStream("hft.ser");
			ObjectOutputStream out = new ObjectOutputStream(fileOut);
				         out.writeObject(d);
				         out.close();
				          fileOut.close();
				      }catch(IOException i)
				      {
				          i.printStackTrace();
				      }
   
	if (ftpconn == true){
		try{
			hftftp.ftp.disconnect();	
			hftftp.bls.close();
			hftftp.logs.close();
			hftftp.pls.close();
		}
		catch (IOException e){
		e.printStackTrace();
		}
	}
		dispose();
	
	}

	void dosecurity(){
		hftsecdlg sec = new hftsecdlg(d.targstr);
		sec.setLocationRelativeTo(null);
		sec.pack();
		sec.setVisible(true);
		try{
			  FileOutputStream fileOut =
				         new FileOutputStream("hft.ser");
				         ObjectOutputStream out =
				                            new ObjectOutputStream(fileOut);
				         out.writeObject(d);
				         out.close();
				          fileOut.close();
				      }catch(IOException i)
				      {
				          i.printStackTrace();
				      }
	}
	
	
	void doinfo(){
		if (hftsrctree.getLastSelectedPathComponent() == null && hfttargtree.getLastSelectedPathComponent() == null){
		JOptionPane.showMessageDialog(contentPane,"Please select a file to edit.","Edit error",JOptionPane.ERROR_MESSAGE);
		return;
		}
		String filename = null;
		if (d.getltc() == "source"){// it is a local file
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) hftsrctree.getLastSelectedPathComponent();
		filename = node.getUserObject().toString();
		File selfile = new File(filename);
		hftfileinfo hfi = new hftfileinfo();
		hfi.pack();
		hfi.setLocationRelativeTo(null);
		hfi.getHftfdname().setText(selfile.getName());
		String me = selfile.getParent();
		Path path = FileSystems.getDefault().getPath(me, selfile.getName());
		if (!swindows){
		PosixFileAttributes attr = null;
		try {
			attr = Files.readAttributes(path, PosixFileAttributes.class);
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		hfi.getHftfdgroup().setText(attr.group().getName());
		hfi.getHftfdperm().setText(PosixFilePermissions.toString(attr.permissions()));
		}
		if (swindows){
			hfi.getHftfdgroup().setText("N/A");
			hfi.getHftfdperm().setText("N/A");
		}
		try {
			BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
			int y = 0;
			hfi.getHftfdsize().setText(Long.toString(attrs.size()));
			hfi.getHftfdmoddate().setText(attrs.lastModifiedTime().toString());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			hfi.getHftfdowner().setText(java.nio.file.Files.getOwner(selfile.toPath()).toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		hfi.setVisible(true);
		}else{// it is a remote file.
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) hfttargtree.getLastSelectedPathComponent();	
		filename=node.getUserObject().toString();
		Boolean nl = node.isLeaf();
		FTPFile tf = new FTPFile(); // create new empty file on the remote system
		FTPFile[] tfa = null;
		String dave1 = d.getsel();
		try {
			if (!nl){hftftp.ftp.cdup();}
	    	FTPListParseEngine engine = hftftp.ftp.initiateListParsing("UnixFTPEntryParser", "-al");
	    	tfa = engine.getFiles();
			//tfa = ftp.listFiles();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //try to list the file; this returns a file array
		for (FTPFile temp : tfa){
			String dave = temp.getName();
			if (temp.getName().equals(d.getsel())){tf = temp;}
		}
		String dave = tf.getName();
		Calendar cl = null;
		hftfileinfo hfi = new hftfileinfo();
		hfi.pack();
		hfi.setLocationRelativeTo(null);
		hfi.getHftfdname().setText(tf.getName());
		hfi.getHftfdgroup().setText(tf.getGroup());
		hfi.getHftfdowner().setText(tf.getUser());
		hfi.getHftfdsize().setText(Long.toString(tf.getSize()));
		cl = tf.getTimestamp();
		String lmdate = Integer.toString(cl.get(Calendar.MONTH))+"/";
		lmdate = lmdate+Integer.toString(cl.get(Calendar.DAY_OF_MONTH))+"/";
		lmdate = lmdate+Integer.toString(cl.get(Calendar.YEAR));
		hfi.getHftfdmoddate().setText(lmdate);
		char rpc = '-';
		char wpc = '-';
		char xpc = '-';
		if (tf.hasPermission(FTPFile.USER_ACCESS,FTPFile.READ_PERMISSION)){rpc = 'r';}
		if (tf.hasPermission(FTPFile.USER_ACCESS,FTPFile.WRITE_PERMISSION)){wpc = 'w';}
		if (tf.hasPermission(FTPFile.USER_ACCESS,FTPFile.EXECUTE_PERMISSION)){xpc = 'x';}
		hfi.getHftfdperm().setText(Character.toString(rpc)+Character.toString(wpc)+Character.toString(xpc));
		hfi.setVisible(true);
		}
		return;
	}
	
	void doedit(){
		if (d.getltc()=="source"){// it is a local file
		if (hftsrctree.getLastSelectedPathComponent() == null && hfttargtree.getLastSelectedPathComponent() == null){
		JOptionPane.showMessageDialog(contentPane,"Please select a file to edit.","Edit error",JOptionPane.ERROR_MESSAGE);
		return;
		}
		 if (d.getsel() != null){
			 	d.setlogfl(false);
				hftedit edit = new hftedit(d, hftftp.ftp);
				edit.pack();
				edit.setLocationRelativeTo(null);
				edit.setVisible(true);
				 }
		}
		if (d.getltc()=="target"){// it is a remote file
			String filename=null;
			if (hftsrctree.getLastSelectedPathComponent() == null && hfttargtree.getLastSelectedPathComponent() == null){
				JOptionPane.showMessageDialog(contentPane,"Please select a file to edit.","Edit error",JOptionPane.ERROR_MESSAGE);
				return;
				}
		if (d.getsel() != null){
			try {
				filename = hftftp.ftp.printWorkingDirectory()+"/"+d.getsel();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				d.setsel(filename);
				d.setlogfl(false);
				hftedit edit = new hftedit(d,hftftp.ftp);
				edit.pack();
				edit.setLocationRelativeTo(null);
				edit.setVisible(true);
				edit.dispose();
				try {
					hftftp.ftp.completePendingCommand();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
			}
	}
	void dohelp(){
		hfthelpdlg hlp = new hfthelpdlg();
		hlp.pack();
		hlp.setLocation(10, 10);
		hlp.setSize(725, 700);
		hlp.setVisible(true);
	}
	static void docopycan(){
		onetree = true;
		int neww = contentPane.getWidth();
		int newh = contentPane.getHeight();
		srctreepane.setSize(neww-6, newh-135);
		srctreepane.setLocation(5,70);
		hftsrctree.setSize(neww-6,newh-135);
		hftstatus.setText("Waiting for user...");
		hftcurrfileprog.setValue(0);
		hftallfileprog.setValue(0);
		if (ftpconn == true){try {
			hftftp.ftp.disconnect();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}}
	}
	
	/* This method list all files and directories in the directory passed if F.  It only lists the first level to make it run faster
	 * and to prevent security issues.  This requires using a custom JTree CellRenderer. 
	 */
	public void getList(DefaultMutableTreeNode node, File f) {
		if (!f.canRead()){
			//HFSstatxt.setText("Invalid access to directory");
			return;
			}
		if (!f.isDirectory()){
			DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
			if (node.getUserObject().toString() != child.getUserObject().toString()){
			node.add(child);
			}
		}
		else{
         DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
			if (node.getUserObject().toString() != child.getUserObject().toString()){
         node.add(child);
         }
         File fList[] = f.listFiles();
         for(int i = 0; i  < fList.length; i++){
        	 if (fList[i].canRead() == false){continue;}
        	 String fn = fList[i].toString();
        	 DefaultMutableTreeNode nn = new DefaultMutableTreeNode(fn);
        	 if (fList[i].isFile()) {nn.setAllowsChildren(false);}
        	 if (fList[i].isDirectory()){nn.setAllowsChildren(true);}
        	 //if (fList[i].getName() == "..") {node.setAllowsChildren(true);}
        	 if (fList[i].canRead() && node.getUserObject().toString() != nn.getUserObject().toString()){
        			 node.add(nn);
        	 }
		}
		}
         
    }

	
	public static void appendNewText(final String txt) {
		  SwingUtilities.invokeLater(new Runnable() {
		     public void run() {
				hftstatus.setText(txt);
				hftstatus.invalidate();
		     }
		  });
		}

	public static void hftresizestuff(){
		int newh = contentPane.getHeight();
		int neww = contentPane.getWidth();
		layeredPane.setSize(neww, newh);
		hftcopyrite.setLocation((neww/2)-92, newh-20);
		getToolBar().setSize(neww-40, getToolBar().getHeight());
		if (onetree) {
			srctreepane.setLocation(5,70);
			srctreepane.setSize(neww-5, newh-150);
		}
		if (onetree == false){
			hftstatus.setLocation(95,newh-55);
			hftstatus.setSize(neww-130,hftstatus.getHeight());
			hftstalbl.setLocation(15,newh-54);
			hftcurrftllbl.setLocation(15,newh-115);
			hftallfileslbl.setLocation(15, newh-84);
			hftcurrfileprog.setLocation(95,newh-85);
			hftcurrfileprog.setSize(neww-130,hftcurrfileprog.getHeight());
			hftallfileprog.setSize(neww-130,hftallfileprog.getHeight());
			hftallfileprog.setLocation(95,newh-115);		
			srctreepane.setLocation(neww/39, 105);
			srctreepane.setSize((neww/2)-90,newh-230);
			hftsrctree.setSize((neww/2)-90, newh-230);
			targtreepane.setLocation((neww/2)+50, 105);
			targtreepane.setSize((neww/2)-90, newh-230);
			hfttargtree.setSize((neww/2)-90,newh-230);
			hfttargtree.setLocation((neww/2)+50, 105);
			panel.setSize(neww-45,23);
			hftsrc2targ.setLocation((neww/2)-30, (newh/4)+6);			
			hfttarg2src.setLocation((neww/2)-30, (newh/4)+ (newh/6));
			hftcopyren.setLocation((neww/2)-30, (newh/4)+ (2*(newh/6)));
			hftcopycan.setLocation((neww/2)-30, (newh/4)+(3*(newh/6)));
		}
		}

public static class MyTreeCellRenderer extends DefaultTreeCellRenderer {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
 * 
 */

	@Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);

        // decide what icons you want by examining the node
        if (value instanceof DefaultMutableTreeNode) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
           // File nf = (File) node.getUserObject()
                if (node.getAllowsChildren()) {
                    setIcon(UIManager.getIcon("FileChooser.newFolderIcon"));
                } else {
                    setIcon(UIManager.getIcon("FileView.fileIcon"));
                }
            }

        return this;
    }

}







class dlgdata implements java.io.Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 
	 */
	private String hn = null; // host name
	private String uid = null; // userid 
	private String pswd = null; // password
	String Targsys = null; //system to connect to
	private String tsel = null; // selected node in target system tree
	private String np = null;
	private DefaultMutableTreeNode p = null;
	private String fl = null;
	public String[] targstr = new String[50];
	private long readlen;
	private byte[] c;
	private boolean connstat = false;
	private File logfile = null;
	public void sethn(String shn){
		hn = shn;
		}
	boolean logfl = false;
	private File crf;
	String ltc = null; // last tree clicked
	private File ksf;
	private String trantype = null;
	public String gethn(){
		return hn.toString();
	}
	public void setuid(String user){
		uid = user;
	}
	public String getuid(){
		return uid.toString();
	}
	public void setpswd(String pass){
		pswd = pass;
	}
	public String getpswd(){
		return pswd;
	}
	public void settarg(String target){
		Targsys = target.toString();
	}
	public String gettarg(){
		return Targsys.toString();
	}
	public String getsel(){
		return tsel;
	}
	public void setsel(String s){
		tsel = s;
	}
	public String getnewpath(){
		return np;
	}
	public void setnewpath(String p){
		np = p;
	}
	public DefaultMutableTreeNode getparent(){
		return p;
	}
	public void setparent(DefaultMutableTreeNode np){
		p = np;
	}
	public void setfl(String l){
		fl = l;
	}
	public String getfl(){
		return fl;
	}
	public void settargst(String[] s){
		targstr = s;
	}
	public String[] gettargst(){
		return targstr;
	}
	public boolean getlogfl(){
		return logfl;
	}
	public void setlogfl(boolean l){
		logfl = l;
	}
	public long getrl(){
		return readlen;
	}
	public void setrl(long rl){
		readlen=rl;
	}
	public byte[] getch(){
		return c;
	}
	public void setch(byte[] ch){
		c = ch;
	}
	public File getcrf(){
		return crf;
	}
	public void setcrf(File nrf){
		crf = nrf;
	}
	public void setlogfile (File l){
		logfile = l;
	}
	public File getlogfile(){
		return logfile;
	}
	public void setconnstat(boolean b){
		connstat = b;
	}
	public boolean getconnstat(){
		return connstat;
	}
	public void setltc(String t){
		ltc = t;
	}
	public String getltc(){
		return ltc;
	}
	public File getksf(){
		return ksf;
	}
	public void setksf(File nrf){
		ksf = nrf;
	}
	public String gettrantype(){
		return trantype; 
	}
	public void settrantype(String type){
		trantype = type;
	}
}
	public JButton getHftexitbtn() {
		return hftexitbtn;
	}
	public JButton getHfthelpbtn() {
		return hfthelpbtn;
	}
	public JButton getHftvlogbtn() {
		return hftvlogbtn;
	}
	public JButton getHftsecbtn() {
		return hftsecbtn;
	}
	public JButton getHftconnbtn() {
		return hftconnbtn;
	}
	public JButton getHftprtbtn() {
		return hftprtbtn;
	}
	public JButton getHftdelbtn() {
		return hftdelbtn;
	}
	public JButton getHftrenbtn() {
		return hftrenbtn;
	}
	public JRadioButton getHftascbtn() {
		return hftascbtn;
	}
	public JRadioButton getHftbinbtn() {
		return hftbinbtn;
	}
	public JRadioButton getHftebcbtn() {
		return hftebcbtn;
	}
	public JCheckBox getHftpsvbtn() {
		return hftpsvbtn;
	}
	public JCheckBox getHftrepbtn() {
		return hftrepbtn;
	}
	public JRadioButton getHftrecbtn() {
		return hftrecbtn;
	}
	public JRadioButton getHftstrmbtn() {
		return hftstrmbtn;
	}
	public JRadioButton getHftfilebtn() {
		return hftfilebtn;
	}
	public JRadioButton getHftdirbtn() {
		return hftdirbtn;
	}
	public JTree getHfttargtree() {
		return hfttargtree;
	}
	public JButton getHftsrc2targ() {
		return hftsrc2targ;
	}
	public JButton getHfttarg2src() {
		return hfttarg2src;
	}
	public JButton getHftcopyren() {
		return hftcopyren;
	}
	public JButton getHftcopycan() {
		return hftcopycan;
	}
	public JTree getHftsrctree() {
		return hftsrctree;
	}
	public static JToolBar getToolBar() {
		return toolBar;
	}
	public JLabel getHftcopyrite() {
		return hftcopyrite;
	}
	public JScrollPane getSrctreepane() {
		return srctreepane;
	}
	public JProgressBar getHftcurrfileprog() {
		return hftcurrfileprog;
	}
	public JScrollPane getTargtreepane() {
		return targtreepane;
	}
	public JPanel getPanel() {
		return panel;
	}
	public JProgressBar getHftallfileprog() {
		return hftallfileprog;
	}
	public JLabel getHftstalbl() {
		return hftstalbl;
	}
	public JLabel getHftcurrftllbl() {
		return hftcurrftllbl;
	}
	public JLabel getHftallfileslbl() {
		return hftallfileslbl;
	}
	public JButton getHftnewfbtn() {
		return hftnewfbtn;
	}
}